var fs = require('fs');
var os = require('os');
var path = require('path');
var OSS = require('ali-oss').Wrapper;
var security = require('./security');



var sleep = function(ms){
	return function(cb){
		setTimeout(cb,ms);
	}
}

var saveFile = function(part){
	return new Promise(function(resolve,reject){
		var stream = fs.createWriteStream(path.resolve("tempfiles", Math.random().toString()));
		stream.on('close',function(){
			resolve(stream.path);
		});
		part.pipe(stream);
	});
}
var saveFileWithBase64 = function (dataBuffer) {
	return new Promise(function(resolve,reject){
		var filePath = path.resolve("tempfiles", Math.random().toString());
		fs.writeFile(filePath, dataBuffer, function(err) {
			err ? reject(err) : resolve(filePath);
		});
	});
}

var getFileKey = async (part,filePath) => {
	var fileMd5 = await security.fileMD5Async(filePath);
	var fext = '';
	var mime = part.mimetype;
	if (mime == 'image/png') fext = ".png";
	if (mime == 'image/jpeg') fext = ".jpg";
	if (mime == 'image/bmp') fext = ".bmp";
	if (mime == 'image/gif') fext = ".gif";
	return fileMd5.substring(0,2) + "/" + fileMd5.substring(2,4) + "/" + fileMd5 + fext;
}


var upload = async (ctx,assetType,key) => {
	let fileUrl = '';
	let opt = ctx.request.body;
	let part = opt.file;
	if (part && part.pipe){
		var filePath = await saveFile(part);
		var fileKey = await getFileKey(part,filePath);
		fileUrl = await ossUpload(filePath,assetType,fileKey);
		fs.unlink(filePath);
	}else if(part && part.length == 4){
		var imgBase64 = part[1];
		if (imgBase64 && imgBase64.indexOf("data:image/jpeg;base64,") == 0){
			var base64Data = imgBase64.replace(/^data:image\/\w+;base64,/, "");
			var dataBuffer = new Buffer(base64Data, 'base64');
			var filePath = await saveFileWithBase64(dataBuffer);
			var fileKey = await getFileKey(part,filePath);
			fileUrl = await ossUpload(filePath,assetType,fileKey);
			fs.unlink(filePath);
		}
	}else{

	}


    return fileUrl;
}

var ossUpload = function (file,assetType,key){
	return new Promise(function(resolve,reject){
		var oss = new OSS({
			accessKeyId: "LTAI0NvpDmpDaIVs",
			accessKeySecret: "Q0uLaNIwZMEquQ6vw3DonwebRLUm6g",
			endpoint: 'http://oss-cn-shenzhen.aliyuncs.com',
			apiVersion: '2013-10-15'
		});
		oss.useBucket('mbs-assets');

		var year = new Date().getFullYear();
		var month = new Date().getMonth() + 1;
		var fileName = security.md5(Math.random().toString()).substr(0,12);
		key = key ? assetType + "/" + key : assetType + "/"+ year +"/" + month + "/" + fileName;

		oss.put(key, file)
		.then(function(ret){
			resolve("http://mbs-assets.oss-cn-shenzhen.aliyuncs.com/" + key);
		}).catch(function (err) {
		  reject(err);
		});
	});
};

module.exports = {
    upload : upload
};
